﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Nate_sRoguelikeGameXNA.GameObjects;
using Nate_sRoguelikeGameXNA.GameObjects.Architecture;
using Nate_sRoguelikeGameXNA.Levels;

namespace Nate_sRoguelikeGameXNA
{
    class MapBlock
    {
        public Point RelativeLocation;
        public Point DrawingOffset = new Point(0, 0);
        public Point Location;
        private List<GameObject> _contents = new List<GameObject>();
        private GameObject TopObject;
        public Level Level { get; set; }
        public bool IsOccupied { get { return _contents.Any(c => c is GameCharacter); } }
        private GameArchitecture _architecture;

        public MapBlock(Level level, Point location)
        {
            Level = level;
            Location = location;
        }

        public GameArchitecture Architecture
        {
            get { return _architecture; }
            set
            {
                _architecture = value;
                ResetTopObject();
            }
        }

        public void AddObject(GameObject gObject)
        {
            _contents.Add(gObject);
            ResetTopObject();
        }

        public void Draw(SpriteBatch spriteBatch)
        {
            Vector2 coords = Game.GetScreenCoords(Location.X + DrawingOffset.X + Game.IngameScreen.DrawingOffset.X,
                                                  Location.Y + DrawingOffset.Y + Game.IngameScreen.DrawingOffset.Y);
            spriteBatch.DrawString(Game.Consolas, TopObject.DisplayCharacter.ToString(),
                Game.GetScreenCoords(Location.X + DrawingOffset.X + Game.IngameScreen.DrawingOffset.X,
                Location.Y + DrawingOffset.Y + Game.IngameScreen.DrawingOffset.Y),
                                   TopObject.DisplayColor, 0, Vector2.Zero, new Vector2(0.5f, 0.5f), SpriteEffects.None, 0);
        }

        public bool IsPassableBy(GameCharacter character)
        {
            return character.ScalingAbility >= Architecture.ScalingDifficulty;
        }

        public void RemoveArchitecture()
        {
            _architecture = Level.BaseArchitecture;
        }
        public void RemoveObject(GameObject gObject)
        {
            _contents.Remove(gObject);
            ResetTopObject();
        }

        public void ResetTopObject()
        {
            var topObject = _contents.Count > 0
                                ? _contents.OrderByDescending(c => c.ZIndex).First()
                                : _architecture;

            if (TopObject != topObject)
            {
                TopObject = topObject;
                Level.ChangedBlocks.Add(this);
            }
        }
    }
}
